package com.mmall.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.mmall.common.ServerResponse;
import com.mmall.dao.ShippingMapper;
import com.mmall.pojo.Shipping;
import com.mmall.service.IShippingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Author 侯俊杰
 * @Date 2018/1/28
 * @Time 21:06
 **/
@Service("iShippingService")
public class ShippingServiceImpl implements IShippingService
{
    @Autowired
    private ShippingMapper shippingMapper;

    @Override
    public ServerResponse add(Integer userId, Shipping shipping)
    {
        shipping.setUserId(userId);
        int rowCount = shippingMapper.insert(shipping);
//        在xml+useGeneratedKeys="true" keyProperty="id" 则会把自动生成的ID赋到shipping对象上
        if(rowCount > 0)
        {
            Map result = Maps.newHashMap();
            result.put("shippingId",shipping.getId());
            return ServerResponse.createBySuccess("新建地址成功",result);
        }
        return ServerResponse.createByErrorMessage("新建地址失败");
    }

    @Override
    public ServerResponse<String> del(Integer userId, Integer shippingId)
    {
        //这样会导致横向越权安全漏洞：登陆后传了一个不属于自己的shippingId,但是却成功del了
//        int resultCount = shippingMapper.deleteByPrimaryKey(shippingId);

        int resultCount = shippingMapper.deleteByShippingIdUserId(userId,shippingId);
        if(resultCount > 0)
        {
            return ServerResponse.createBySuccess("删除地址成功");
        }
        return ServerResponse.createByErrorMessage("删除地址失败");

    }

    @Override
    public ServerResponse<String> update(Integer userId, Shipping shipping)
    {
        shipping.setUserId(userId);
        //同样存在横向越权问题
        int rowCount = shippingMapper.updateByShipping(shipping);
        if(rowCount > 0)
        {
            Map result = Maps.newHashMap();
            return ServerResponse.createBySuccess("更新地址成功");
        }
        return ServerResponse.createByErrorMessage("更新地址失败");

    }

    @Override
    public ServerResponse<Shipping> select(Integer userId, Integer shippingId)
    {
        Shipping shipping = shippingMapper.selectByShippingIdUserId(userId,shippingId);
        if(shipping == null)
        {
            return ServerResponse.createByErrorMessage("无法查询到该地址");
        }
        return ServerResponse.createBySuccess("查询地址成功",shipping);
    }

    @Override
    public ServerResponse<PageInfo> list(Integer userId, int pageNum, int pageSize)
    {
        PageHelper.startPage(pageNum,pageSize);
        List<Shipping> shippingList = shippingMapper.selectByUserId(userId);
        PageInfo pageInfo = new PageInfo(shippingList);
        return ServerResponse.createBySuccess(pageInfo);
    }


}
